<template>
  <div class="page-container">
    <!-- 遮罩层 -->
    <div
      class="mask"
      v-if="isLoading"
    >
      <div class="mask-content">
        <p class="mask-text">处理中，请稍候...</p>
      </div>
    </div>

    <div class="content-wrapper">
      <!-- 筛选栏批量刊登按钮 -->
      <div class="filter-content" v-if="showSearch">
        <div class="filter-item">
          <div class="label-content" style="display: flex; align-items: center;">
            <el-input class="search-input-width   elliptical-input" v-model.trim="baseTable.tableReqDto.title" clearable placeholder="产品关键字"></el-input>
            <el-input class="search-input-width   elliptical-input" v-model.trim="baseTable.tableReqDto.originAsin" clearable placeholder="产品ASIN码"></el-input>
<!--            <el-input class="search-input-width   elliptical-input" v-model.trim="baseTable.tableReqDto.originPrice" clearable placeholder="价格"></el-input>-->
            <el-select
              class="elliptical-select"
              placeholder="请选择店铺"
              v-model.trim="baseTable.tableReqDto.templateId"
              clearable
              style="width: 150px;"
              @change="baseTable.onSearch">
              <el-option
                v-for="item in templateList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>

            <el-select
              class="elliptical-select"
              placeholder="请选择状态"
              v-model.trim="baseTable.tableReqDto.status"
              clearable
              style="width: 150px;"
              @change="baseTable.onSearch">
              <el-option key="0" label="待编辑" value="editinit"></el-option>
              <el-option key="1" label="待刊登" value="init"></el-option>
              <el-option key="2" label="待发布" value="submit"></el-option>
              <el-option key="3" label="已发布" value="finish"></el-option>
              <el-option key="4" label="失败" value="error"></el-option>
            </el-select>

            <el-button style="height: 34px" :auto-insert-space="true" type="primary" round @click="baseTable.onSearch">
              <el-icon style="margin-right: 5px;height: 34px"><Search /></el-icon>搜索
            </el-button>
            <el-button @click="resetFilter" round style="height: 34px; margin-left: 0px">
              <el-icon  style="margin-right: 5px;height: 34px"><RefreshLeft /></el-icon>
              重置
            </el-button>
          </div>
        </div>
      </div>

      <div class="products-box">
        <div class="products-container">
          <div class="products-list" ref="productsListDiv">
            <!-- 产品卡片 -->
            <div class="product-item" v-for="item in baseTable.tableData" :key="item.id" >
              <div class="fan-publish-container" v-if="item.status == 'init'">
                <div class="fan-publish-button" @click.stop="singleProductFunction(item)">
                  <span class="fan-publish-text">
                      <el-icon><Upload /></el-icon>
                  </span>
                </div>
              </div>


              <div class="publish-btn-container2"  :class="{ 'selected': isSelected(item) }">
                <div class="publish-btn2" @click.stop="handleCardClick(item)" >
                  <span class="publish-text2">
                      <el-icon><Check /></el-icon>
                  </span>
                </div>
              </div>

              <div class="product-item-img" @click="handleCardClick(item)"  >
                <!-- 编辑按钮 -->
                <div class="edit-btn" @click.stop="onEditTemplate(item)" v-if="item.status == 'editinit' || item.status == 'init'">
                  <el-icon><EditPen /></el-icon>
                </div>

                <div class="img-slide-wrap2">
                  <el-image
                    class="img cursor-pointer"
                    :src="item.thumbnail"
                    :fit="'cover'"
                    @click="handleCardClick(item)"
                  ></el-image>
                </div>
              </div>

              <div style="padding: 12px">
                <div class="product-name" @click="handleCardClick(item)" >{{ item.title }}</div>
                <div class="product-info" @click="handleCardClick(item)" >
                  <div style="display: flex;justify-content: space-between">
                    <p style="color:#626EFB;font-size: 14px">＄{{item.originPrice}}</p>
                    <p style="color:#8C8C8C"  v-if="item.status=='editinit'">待编辑</p>
                    <p style="color:#FF9800"  v-if="item.status=='init'">待刊登</p>
                    <p style="color:#2196F3"  v-if="item.status=='submit'">待发布</p>
                    <p style="color:#4CAF50" v-if="item.status=='finish'">已发布</p>
                    <p style="color:#F44336"  v-if="item.status=='error'">失败</p>
                  </div>
                  <p>
                    <span>原ASIN：</span>
                    <span>{{ item.originAsin }}</span>
                  </p>
                  <p>
                    <span>刊登店铺：</span>
                    <span>{{ item.storeName }}/{{ item.marketplaceName }}</span>
                  </p>
                </div>
              </div>
            </div>
          </div>
<!--          <div style="height: 50px"></div>-->
        </div>
      </div>

      <pre-submit-listing2
        ref="editTankuang"
        @dialog-closed="handleDialogClosed"
        :product-id="currentRow?.bsId || ''"
        :product-dto="currentRow || null"
      ></pre-submit-listing2>
    </div>

    <!-- 分页组件 - 悬浮在底部 -->
    <div class="floating-pagination">
      <div style="padding-left: 20px">
        <el-button
          :round="true"
          @click="handleSelectAll"
        >
          <!-- 根据选择状态动态显示按钮文本 -->
          {{ isAllSelected ? '取消全选' : '全选' }}
        </el-button>
        <el-button
          :round="true"
          type="success"
          @click="openBatchPublishDialog"
          :loading="submitListingLoading"
          :disabled="selectedProductIds.length === 0"
        >
          <el-icon><Upload /></el-icon>
          <span>刊登</span>
        </el-button>
        <el-button
          :round="true"
          type="danger"
          :disabled="selectedProductIds.length === 0"
          @click="batchDelete">
          <el-icon><Delete /></el-icon>
          <span>删除</span>
        </el-button>
      </div>
      <div style="padding-right: 20px">
        <table-pagination
          :hideOnSinglePage="false"
          :pagination="baseTable.dataPagination"
          @change="baseTable.onPaginationChange"
        />
      </div>
    </div>

    <el-dialog
      v-model="dialogVisible"
      title="刊登-选择店铺和模板"
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="dialog-content">
        <el-form-item label="选择店铺" label-width="100px" :required="true">
          <el-select
            v-model="selectedStore"
            clearable
            style="width: 100%;"
          >
            <el-option
              v-for="item in storeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

<!--        <el-form-item label="选择模板" label-width="100px" :required="true">-->
<!--          <el-select-->
<!--            v-model="selectedTemplate"-->
<!--            clearable-->
<!--            style="width: 100%;"-->
<!--          >-->
<!--            <el-option-->
<!--              v-for="item in templateList"-->
<!--              :key="item.value"-->
<!--              :label="item.label"-->
<!--              :value="item.value"-->
<!--            ></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->

        <div class="selected-count" style="margin-top: 10px; color: #666;">
          已选中 {{ selectedProductAsins.length }} 个产品
        </div>
      </div>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="selectStore">确认刊登</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import TablePagination from '@/plugins/pair/table-pagination.vue'
import PreSubmitListing2 from "@/plugins/pair/pre-submit-listing2.vue";
import {Delete, EditPen, Upload, Check, RefreshLeft, Search} from '@element-plus/icons-vue'
import { useDefineTable } from '@/plugins/util/global-variable2'
import {
  deleteSubmitListing,
  listingTemplateNotPage,
  preSubmitListingPage,
  singleProduct,
  submitListing,
  editsubmitListing,
  preSubmitListing,
  storeAuthorizeList, batchsubmitListing, getProduct, deleteSubmitListingAll
} from '@/api/common'
import { ElMessage, ElCheckbox, ElMessageBox } from 'element-plus'
import { globalSubmitListingEvent } from '@/plugins/util/constants'
import { HttpAsk } from '@/plugins/util/axios'
import { ref, reactive, onMounted, computed } from 'vue'

// 遮罩层控制变量
const isLoading = ref(false);

const baseTable = useDefineTable({
  tableReqDto: {
    name: '',
    pageSize:12,
    templateId: '',
    regions: [],
  },
  request: preSubmitListingPage,
  tableColumns: [
    { colKey: 'title', title: '产品信息', width: '400' },
    { colKey: 'salePrice', title: '刊登价格', align: 'center' },
    { colKey: 'saleInventory', title: '刊登库存', align: 'center' },
    { colKey: 'storeName', title: '刊登到店铺', align: 'center' },
    { colKey: 'createTime', title: '添加时间', align: 'center', date: true },
    { colKey: 'opt', title: '操作', width: '150', align: 'center' },
  ],
})

defineProps({
  height: {
    type: String,
    default: 'calc(100vh - 380px)',
  },
  showSearch: {
    type: Boolean,
    default: true,
  },
})

const selectedProductIds = ref<string[]>([])
const selectedProductAsins = ref<string[]>([])

// 判断是否选中的方法
const isSelected = (item: any) => {
  return selectedProductIds.value.includes(item.id);
}

// 计算属性：判断是否全选
const isAllSelected = computed(() => {
  // 有数据且已选数量等于当前页总数量时为全选状态
  return baseTable.tableData.length > 0 &&
    selectedProductAsins.value.length === baseTable.tableData.length;
})

// 全选/取消全选方法
const handleSelectAll = () => {
  if (isAllSelected.value) {
    // 取消全选
    selectedProductIds.value = [];
    selectedProductAsins.value = [];
  } else {
    // 全选当前页所有产品
    const allIds = baseTable.tableData.map(item => item.id);
    const allAsins = baseTable.tableData.map(item => item.originAsin);
    // 使用Set确保数据不重复
    selectedProductIds.value = [...new Set(allIds)];
    selectedProductAsins.value = [...new Set(allAsins)];
  }
}

// 批量删除选中产品
const batchDelete = () => {
  if (selectedProductIds.value.length === 0) {
    ElMessage.warning('请先选择要删除的产品');
    return;
  }

  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedProductIds.value.length} 个产品吗？`,
    '删除确认',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    // 调用批量删除API
    deleteSubmitListingAll(selectedProductIds.value).then(() => {
      ElMessage.success('删除成功');
      // 刷新列表
      baseTable.exeRequest();
      // 清空选择
      selectedProductIds.value = [];
      selectedProductAsins.value = [];
    }).catch(() => {
      ElMessage.error('删除失败，请重试');
    });
  }).catch(() => {
    // 取消删除
  });
}

const handleDialogClosed = () => {
  baseTable.exeRequest();
}
// 处理分页变化时重置全选状态
const handlePaginationChange = (pagination: any) => {
  baseTable.onPaginationChange(pagination);
  // 分页切换时清空选择，避免跨页选择
  selectedProductIds.value = [];
  selectedProductAsins.value = [];
}

// 重置筛选条件
const resetFilter = () => {
  baseTable.tableReqDto.templateId = '';
  baseTable.tableReqDto.title = '';
  baseTable.tableReqDto.originAsin = '';
  baseTable.tableReqDto.originPrice = '';
  baseTable.onSearch();
  // 重置选择状态
  selectedProductIds.value = [];
  selectedProductAsins.value = [];
}

const dialogVisible = ref(false);
const selectedStore = ref('');
const selectedRowId = ref('');
const selectedRowAsin = ref('');
const selectedTemplate = ref('');

const currentRow = ref<any>(null);
const editTankuang = ref<InstanceType<typeof PreSubmitListing2>>();
const submitListingLoading = ref(false)
const templateList = reactive<any[]>([])
const storeList = reactive<any[]>([])

const onDeleteSubmitListing = (row: any) => {
  deleteSubmitListing(row.id).then((res) => {
    globalSubmitListingEvent.value = res.timestamp + ''
    baseTable.exeRequest()
    selectedProductIds.value = selectedProductIds.value.filter(id => id !== row.id)
    selectedProductAsins.value = selectedProductAsins.value.filter(asin => asin !== row.originAsin)
  })
}

const reqListingTemplateNotPage = () => {
  listingTemplateNotPage().then((res: any) => {
    res.data.forEach((ite) => {
      templateList.push({
        value: ite.id,
        label: ite.name,
      })
    })
  })
}

const reqListingStorePage = () => {
  storeAuthorizeList({ pageNo: 1, pageSize: 50 }).then((res: any) => {
    res.data.content.forEach((ite) => {
      storeList.push({
        value: ite.id,
        label: ite.name,
      })
    })
  })
}

const onEditTemplate = (row: any) => {
  if(row.status=='editinit'){
    getProduct(row.originProductId).then((res) => {
      currentRow.value = res.data;
      if (editTankuang.value) {
        editTankuang.value.onOpen();
      }
    })
  }else{
    editsubmitListing({ asin: row.originAsin }).then(res => {
      currentRow.value = res.data;
      if (editTankuang.value) {
        editTankuang.value.onOpen();
      }
    })
  }
}

const selectStore = () => {
  if (selectedStore.value) {
    isLoading.value = true;
    let params = {};
    params.storeIds = [selectedStore.value]
    params.templateIds = [selectedTemplate.value]
    params.asins =  [...selectedProductAsins.value];
    batchsubmitListing(params)
      .then((res) => {
        dialogVisible.value = false
        ElMessage.success('提交成功')
        selectedProductIds.value = []
        selectedProductAsins.value = []
      })
      .catch(() => {
        ElMessage.error('提交失败，请重试')
      })
      .finally(() => {
        isLoading.value = false;
        setTimeout(() => {
          baseTable.exeRequest();
        }, 500);
      })
  }
}

const singleProductFunction = (row: any) => {
  selectedStore.value = '';
  selectedTemplate.value = '';
  selectedProductAsins.value = [row.originAsin]
  dialogVisible.value = true;
}




const openBatchPublishDialog = () => {
  selectedStore.value = '';
  selectedTemplate.value = '';
  dialogVisible.value = true;
}

const handleCardClick = (item: any) => {
  const id = item.id
  const isSelected = selectedProductIds.value.includes(item.id)
  if (isSelected) {
    selectedProductIds.value = selectedProductIds.value.filter(_id => _id !== id)
    selectedProductAsins.value = selectedProductAsins.value.filter(asin => asin !== item.originAsin)
  } else {
    selectedProductIds.value.push(item.id)
    selectedProductAsins.value.push(item.originAsin)
  }
}

const handleCheckboxChange = (isChecked: boolean, item: any) => {
  const id = item.id
  if (isChecked) {
    if (!selectedProductIds.value.includes(item.id)) {
      selectedProductIds.value.push(id)
      selectedProductAsins.value.push(item.originAsin)
    }
  } else {
    selectedProductIds.value = selectedProductIds.value.filter(_id => _id !== id)
    selectedProductAsins.value = selectedProductAsins.value.filter(asin => asin !== item.originAsin)
  }
}

onMounted(() => {
  reqListingTemplateNotPage()
  reqListingStorePage()
})

const onProductDetail = (row: any) => {
  // 产品详情逻辑
}
</script>

<style scoped lang="scss">
.content-wrapper {
  padding-bottom: 20px;
}

/* 悬浮分页样式 */
.floating-pagination {
  position: sticky ;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: rgba(255, 255, 255, 0.95);
  padding: 12px 0;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  z-index: 900;
  display: flex;
  margin-top: -10px;
  justify-content: space-between;
  align-items: center;
}

/* 遮罩层样式 */
.mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 9999;
  display: flex;
  justify-content: center;
  align-items: center;
}

.mask-content {
  text-align: center;
  background-color: white;
  padding: 30px 50px;
  border-radius: 8px;
}

.mask-text {
  margin-top: 15px;
  font-size: 16px;
  color: #333;
}

/* 其他样式保持不变 */
.edit-btn {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #6169FF;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  cursor: pointer;
  opacity: 0;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  z-index: 2;
}

.product-item:hover .edit-btn {
  opacity: 1;
}

.edit-btn:hover {
  background-color: #fff;
  color: #6169FF;
  transform: translate(-50%, -50%) scale(1.1);
}


.publish-btn {
  position: absolute;
  top: -50px;
  right: -50px;
  width: 60px;
  height: 60px;
  background-color: #6169FF;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  cursor: pointer;
  transition: all 0.3s ease;
  transform: rotate(45deg);
  opacity: 0;
}

.publish-text {
  transform: rotate(-45deg);
  font-size: 16px;
  font-weight: 500;
  width: 80px;
  text-align: center;
  margin-left:2px;
  margin-top: 35px;
}

/* 已收藏状态 - 始终显示 */
.publish-btn-container.always-visible .publish-btn {
  top: -30px;
  right: -30px;
  opacity: 1;
}

/* 未收藏状态 - 鼠标悬停时显示50%透明度 */
.publish-btn-container.hover-visible .publish-btn {
  top: -30px;
  right: -30px;
  opacity: 0;
}

.product-item:hover .publish-btn-container.hover-visible .publish-btn {
  opacity: 0.5;
}

.publish-btn-container2 {
  position: absolute;
  top: 0;
  left: 0;
  width: 60px;
  border-radius: 5px;
  height: 60px;
  overflow: hidden;
  z-index: 2;
}

.publish-btn2 {
  position: absolute;
  top: -50px;
  left: -50px;
  width: 60px;
  height: 60px;
  background-color: #6169FF;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  cursor: pointer;
  transition: all 0.3s ease;
  transform: rotate(45deg);
  opacity: 0;
}

.publish-text2 {
  transform: rotate(-45deg);
  font-size: 16px;
  font-weight: 500;
  width: 80px;
  text-align: center;
  margin-left:40px;
  margin-top: 5px;
}

.product-item:hover .publish-btn2 {
  top: -30px;
  left: -30px;
  opacity: 0.5;
}

.selected {
  .publish-btn2 {
    top: -30px;
    left: -30px;
    opacity: 1!important;;
  }
}

.products-box {
  border-radius: 5px;
  padding: 8px;
  min-height: 800px;
  border: 1px solid #DDDFE6;
  background-color: #F7F9FE;
}

.products-container {
  max-width: 1880px;
  margin: 0 auto;
}

.products-list {
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;
  //justify-content: space-between;
  gap: 12px;
}

.product-item {
  height: 314px;
  position: relative;
  flex: 0 0 calc((100% - 6 * 12px) / 7);
  box-sizing: border-box;
  border: 1px solid #DDDFE6;
  background-color: white;
  border-radius: 6px;
  transition: all 0.3s ease;
  overflow: hidden;
}

.product-item.filler {
  visibility: hidden;
  border: none;
  padding: 0;
}

.product-item:hover {
  box-shadow: 0 3px 8px rgba(0, 0, 0, 0.06);
  transform: translateY(-1px);
}

.product-item-img {
  width: 100%;
  aspect-ratio: 1 / 1;
  overflow: hidden;
  margin-bottom: 8px;
  position: relative;
}

.product-item-img .img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.product-item:hover .product-item-img .img {
  transform: scale(1.05);
}

.product-name {
  font-size: 13px;
  line-height: 1.3;
  height: 2.6em;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  margin-bottom: 6px;
}

.product-info {
  font-size: 12px;
}

.product-info p {
  margin: 3px 0;
  line-height: 1.4;
}

.table-pagination{
  margin-top: 0px!important;
}

/* 响应式断点：适配小于1080p的屏幕 */
/* 1. 屏幕宽度 ≤1600px（如笔记本1366×768）：一行5个 */
@media screen and (max-width: 1600px) {
  .products-container {
    max-width: 1560px;
  }
  .product-item {
    flex: 0 0 calc((100% - 4 * 12px) / 5); /* (1560 - 4*12)/5 ≈ 302px */
  }
}

/* 2. 屏幕宽度 ≤1366px：一行4个 */
@media screen and (max-width: 1366px) {
  .products-container {
    max-width: 1320px;
  }
  .product-item {
    flex: 0 0 calc((100% - 3 * 12px) / 4); /* (1320 - 3*12)/4 ≈ 327px */
  }
}

/* 3. 屏幕宽度 ≤1024px（平板横屏）：一行3个 */
@media screen and (max-width: 1024px) {
  .products-container {
    max-width: 980px;
  }
  .product-item {
    flex: 0 0 calc((100% - 2 * 12px) / 3); /* (980 - 2*12)/3 ≈ 318px */
  }
}

/* 4. 屏幕宽度 ≤768px（平板竖屏/手机横屏）：一行2个 */
@media screen and (max-width: 768px) {
  .products-container {
    max-width: 720px;
  }
  .product-item {
    flex: 0 0 calc((100% - 1 * 12px) / 2); /* (720 - 12)/2 = 354px */
  }
}

/* 5. 屏幕宽度 ≤480px（手机竖屏）：一行1个 */
@media screen and (max-width: 480px) {
  .products-container {
    max-width: 100%;
  }
  .product-item {
    flex: 0 0 100%; /* 全屏宽度 */
  }
}

.fan-publish-container {
  position: absolute;
  top: 0;
  right: 0;
  width: 80px;
  height: 80px;
  overflow: hidden;
  z-index: 2;
}

.fan-publish-button {
  position: absolute;
  top: -30px;
  right: -30px;
  width: 60px;
  height: 60px;
  background-color: #6169FF;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  cursor: pointer;
  transition: all 0.3s ease;
  transform: rotate(45deg);
  opacity: 0;
}

.product-item:hover .fan-publish-button {
  opacity: 1;
}

.fan-publish-text {
  transform: rotate(-45deg);
  font-size: 16px;
  font-weight: 500;
  width: 80px;
  text-align: center;
  margin-left: 3px;
  margin-top: 35px;
}

</style>

